//
//  GeneralAuditVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/3/1.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit

class GeneralAuditForm: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var type4web = false
    
    var tableView: UITableView = {
        var v = UITableView()
        return v
    }()
    
    var dataArray = [AuditFlowContent]()
    
    var isUseTab = false
    
    var currTabIndex = 0
    // tab 的数据源
    var tabDataArr = [[AuditFlowContent]]()
    var showTabDataArr = [AuditFlowContent]()

    lazy var tabSectionHeader: GeneralAuditTabSection = {
        let header = GeneralAuditTabSection()
        header.selectBlock = { [weak self] index in
            guard let self = `self` else { return }
            self.currTabIndex = index
            self.showTabDataArr = self.tabDataArr[index]
            self.tableView.reloadData()
        }
        return header
    }()
    
    
    var model = ToDoModel(JSON:["":""])!
    
    var formItems = [TodoFormItems]()
 
    var appr = AuditProcessAppear()
    
    var webNeedEdit = false // 网页里有需要修改的字段，同意前需要调用网页保存
    
    var headerVV:GeWebAuditHeader = {
        var v = GeWebAuditHeader(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: KSGlobal.screenH - 260))
        return v
    }()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.title = self.model.vocNm
        
        self.view.addSubview(tableView)
        tableView.frame = self.view.bounds
        tableView.delegate = self
        tableView.dataSource = self
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 150, right: 0)
        if model.auditReturnType == "SUCCESS" || model.auditReturnType == "ERROR" {
            KSNetwork.shared.doRequest(API.auditFlow(.WflowUpdateNOTIFY(instanceId: model.instanceId.unwrap, id: model.id.unwrap)),showHud: false) { (data:BaseResult<OperateResult>) in
                
            }
        }
        
        if type4web {
            tableView.rowHeight = KSGlobal.screenH - 260
        } else {
            tableView.estimatedRowHeight = 100
            tableView.rowHeight = UITableView.automaticDimension
        }
        
        
        tableView.separatorStyle = .none
        tableView.tableFooterView = UIView()
        tableView.backgroundColor = Theme.awModuleBgColor
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        

        self.tableView.register(GeneralSepeCell.self, forCellReuseIdentifier: GeneralSepeCell.identifier)
        self.tableView.register(AuditSecHeader.self, forHeaderFooterViewReuseIdentifier: AuditSecHeader.identifier)
        self.tableView.register(AuditItemCell.self, forCellReuseIdentifier: AuditItemCell.identifier)
        self.tableView.register(AuditItemCell2.self, forCellReuseIdentifier: AuditItemCell2.identifier)
        self.tableView.register(GlobalSectionHeader.self, forHeaderFooterViewReuseIdentifier: GlobalSectionHeader.identifier)
        self.tableView.register(GeneralAuditTabFooter.self, forHeaderFooterViewReuseIdentifier: GeneralAuditTabFooter.identifier)
        dealFooterAuditFlow(model: model) { [weak self] info, chooseUsers in
            
            guard let self = `self` else { return }

            // 单据信息
            var oneMain = AuditFlowContent(JSON: ["":""])!
            oneMain.title = "基本信息"
            oneMain.type = "1"
            
            let fitems = info.formItems
            self.formItems = fitems
            let formItems = fitems.filter { $0.perm != "H" }
            
            self.configHeader()
            
            let showmarr = fitems.compactMap { onex in
                //必填
                var mustx = "false"
                if let pr = onex.props {
                    if pr.requiredx == "true" && onex.perm == "E" {
                        mustx = "true"
                    }
                }
                
                let newx = StringTypeCombine(conType: .content,pre: onex.title.unwrap, suf: onex.value.unwrap, perm:  onex.perm.unwrap, must: mustx)
                return newx
            }
            
            oneMain.mainArr = showmarr
            self.dataArray.append(oneMain)
            
            
            if let report = info.report_url, report.count > 0 {
                var oneReport = AuditFlowContent(JSON: ["":""])!
                oneReport.title = "报表"
                oneReport.type = "3"
                oneReport.report = report
                self.dataArray.append(oneReport)
            }
            
            if info.file.count > 0 {
                var oneFile = AuditFlowContent(JSON: ["":""])!
                oneFile.title = "附件"
                oneFile.type = "4"
                var nfffArr = [FileModel]()
                for ifff in info.file {
                    var nfff = FileModel(JSON:["":""])!
                    nfff.file_name = ifff.file_name
                    nfff.pic_url = ifff.file_url
                    nfffArr.append(nfff)
                }
                
                oneFile.files = nfffArr
                
                self.dataArray.append(oneFile)
            }
            
            self.isUseTab = info.mxtable.count > 1
            
            if self.isUseTab {
                var tabOne = AuditFlowContent(JSON: ["":""])!
                tabOne.type = "10"
                self.dataArray.append(tabOne)
            }
            
            var tmpTabDataArr = [[AuditFlowContent]]()
            var tmpTabTitles = [String]()
            
            for ittt in info.mxtable {
                
                var tmpSubTabDataArr = [AuditFlowContent]()
                tmpTabTitles.append(ittt.c_group_title.standby(ittt.table_title.unwrap))
                
                for ondd in ittt.table {
                    var oneDet = AuditFlowContent(JSON: ["":""])!
                    oneDet.title = "\(ittt.table_title.unwrap)(\(ondd.rows.intWrap + 1))"
                    oneDet.type = "2"
                    //                        let fitems = info.formItems
                    //                        var formItems = fitems.filter { $0.perm != "H" }
                    let dditems = ondd.data
                    
                    var showDarr = dditems.compactMap { StringTypeCombine(conType: .content, pre: $0.comments.unwrap, suf: $0.value.unwrap, perm: "R") }
                    if ondd.dt_table.count > 0 {
                        
                        var moreInfos = [AuditFlowContent]()
                        for (idx, oneTab) in ondd.dt_table.enumerated() {
                            var oneMain = AuditFlowContent(JSON: ["":""])!
                            oneMain.title = "明细\(idx + 1)"
                            oneMain.type = "1"
                            
                            for (_, oneRow) in oneTab.data.enumerated() {
                                let newOne = StringTypeCombine(conType: .content, pre: oneRow.comments.unwrap, suf: oneRow.value.unwrap, perm: "R")
                                oneMain.mainArr.append(newOne)
                            }
                            
                            moreInfos.append(oneMain)
                        }
                        
                        showDarr.append(StringTypeCombine(conType: .more, pre: "点击查看详情", perm: "R", moreInfo: moreInfos))
                    }
                    oneDet.detailArr = showDarr
                    
                    if self.isUseTab {
                        
                        oneDet.title = "明细(\(ondd.rows.intWrap + 1))"
                        tmpSubTabDataArr.append(oneDet)
                        
                        var lastFooter = AuditFlowContent(JSON: ["":""])!
                        lastFooter.type = "11"
                        tmpSubTabDataArr.append(lastFooter)
                    } else {
                        /// 没有多个 tab 的保留旧样式
                        self.dataArray.append(oneDet)
                    }
                }
                
                if self.isUseTab {
                    tmpTabDataArr.append(tmpSubTabDataArr)
                }
            }
            
            if self.isUseTab {
                self.tabDataArr = tmpTabDataArr
                
                self.tabSectionHeader.titles = tmpTabTitles
                
                self.showTabDataArr = self.tabDataArr.first!
            }
             
            
            let checkV = configCheckView(selfmodel: self.model, chooseuser: chooseUsers, appr: self.appr, pointsResult:  info.progress, info: info, formItems: formItems, dataArray: self.dataArray, webNeedEdit:  self.webNeedEdit, parentVc: self)
            
            self.tableView.tableFooterView = checkV.0
            self.tableView.reloadData()
            
            if self.appr.jueseType != .viewer {
                self.view.addSubview(checkV.1)
                checkV.1.snp.makeConstraints { make in
                    make.left.right.bottom.equalToSuperview()
                    make.height.equalTo(70)
                }
            }
        }
    }
 
    func configHeader() {
        if type4web {
            self.tableView.tableHeaderView = headerVV
            
            let uuu = model.vouUrl.unwrap + model.vouId.unwrap
            
            //can
            
            let can = self.formItems.filter{ $0.perm == "E" }.compactMap{ $0.columnName }.joined(separator: "~")
            webNeedEdit = can.count > 0
            let hhh = self.formItems.filter{ $0.perm == "H" }.compactMap{ $0.columnName }.joined(separator: "~")
            let rrr = self.formItems.filter{ $0.perm == "E" && $0.props?.requiredx == "true" }.compactMap{ $0.columnName }.joined(separator: "~")
            

            KSLog("can")
            KSLog(can)
            KSLog("hhh")
            KSLog(hhh)
            KSLog("rrr")
            KSLog(rrr)
            var rlll =  "\(USERINFO.pcDomain.unwrap)mobileOpenHtml?token=\(TOKEN)&authid=\(AUTHID)&url=\(uuu)&canfiled=\(can)&hidefiled=\(hhh)&required=\(rrr)"
            
            // 发起人节点都可以编辑
            if model.nodeId == "root" {
                rlll += "&is_root=1"
            }
            
            headerVV.reportUrl = rlll
          
            headerVV.startShowContent()
  
        }
    }
}


func configBtnType(selfmodel: ToDoModel, info: TodoResult) -> OperationPerm? {
    if selfmodel.auditReturnType == "INFO" {
        // 知会类型，按钮只有评论
        var cc = BtnPerm(JSON:["":""])!
        cc.alisa = "评论"
        cc.show = true
        
        var yy = BtnPerm(JSON:["":""])!
        yy.alisa = "已阅"
        yy.show = true
        
        var opP = OperationPerm(JSON:["":""])!
        opP.comment = cc
        opP.readed = yy
        
        return opP
    } else {
        return info.operationPerm
    }
}
 
func configCheckView(selfmodel: ToDoModel, chooseuser: [ChooseUsers], appr: AuditProcessAppear, pointsResult: [TodopProgress], info: TodoResult, formItems: [TodoFormItems], dataArray: [AuditFlowContent], webNeedEdit: Bool, parentVc: UIViewController) -> (AuditProcessPointV, AuditOpeView) {
  
    let bbtty = configBtnType(selfmodel: selfmodel, info: info)
    let auditProcessV = AuditProcessPointV(points: pointsResult, btnType: bbtty, appr: appr, vc: parentVc)
    
    auditProcessV.historyBtn.addTouchUpInSideAction { _ in
        
        KSNetwork.shared.doRequest(API.auditFlow(.WflowgetVouAudListOld(voc_cd: selfmodel.vocCd.unwrap, vou_id: selfmodel.vouId.unwrap))) {  (data:BaseResult<HistoryAuditModel>) in
            
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    var allArr = [nameAndModel<HistoryAuditModel>]()
                    
                    for item in infos {
                        let one_x = nameAndModel(shows: ["提交人", "\(item.submit_nm.unwrap)", "提交日期", "\(item.submit_dt.unwrap)", "岗位", "\(item.post_nm.unwrap)", "人员", "\(item.staff_nm.unwrap)", "审核日期", "\(item.audit_dt.unwrap)", "审核状态", "\(item.verfymark.unwrap)", "审核意见", "\(item.memo.unwrap)"], model: item)
                        allArr.append(one_x)
                    }
                    
                    let cle:(nameAndModel<HistoryAuditModel>)->() = { one in
                        
                        
                    }
                    
                    let vc = KSSingleSelectUtil.initWithNav(title: "历史审核", allArr: allArr, backClosure: cle)
                    parentVc.present_FullScreen(to: vc)
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    
    let auditOpeV = AuditOpeView()
    auditOpeV.setBtnArr(appr: appr)
    if appr.jueseType == .viewer {
        auditOpeV.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 0)
    } else {
        auditOpeV.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 60)
    }
    
    auditOpeV.operateBtnBlock = { btntitle in
        // 单据校验
        var json = ""
        var jsonNew = ""
  
        if let provc = parentVc as? ConfigMenuForm {//配置菜单页面
        
            let vali = Validation()
            // 定制页面  配置菜单
            var editFormI:[TodoFormItems]!
            
            if selfmodel.nodeId == "root" {
                editFormI = formItems
            } else {
                editFormI = formItems.filter{ $0.perm == "E" }
            }
            
            for i in 0..<editFormI.count {
                var formone = editFormI[i]
                
                formone.value = any2Str(provc.main[formone.columnName.unwrap])
                 
                if let pr = formone.props, pr.requiredx == "true" {
                    vali.required(value: formone.value, msg: "\(formone.title.unwrap)不为空!")
                }
              
                let oneeee = dictionaryToJson(formone.dictionaryRepresentation())
                
                if i == editFormI.count - 1 {
                    jsonNew = "[\(jsonNew)\(oneeee)]"
                } else {
                    jsonNew = jsonNew + oneeee + ","
                }
             
            }
            
            if btntitle == "同意" {
                guard vali.validate() else {
                    return
                }
            }
            continueBtnAc()
        } else {
            // 常规页面
            if let ggvc = parentVc as? GeneralAuditForm {
                let vali = Validation()
                for i in 0..<formItems.count {
                    let id = formItems[i].id.unwrap
                    var vv = ""
                    if ggvc.dataArray.count > 0 {
                        let theone = ggvc.dataArray.first!.mainArr[i]
                        
                        vv = theone.suf
                        
                        if theone.must == "true" {
                            vali.required(value: vv, msg: "\(theone.pre)不为空!")
                        }
                        
                    }
                    //配合服务端转换
                    let replacevv = vv.replacingOccurrences(of: "\n", with: "%OA")
                    
                    let dd = "{\"\(id)\":\"\(replacevv)\"}"
                    
                    if i == formItems.count - 1 {
                        json = "[\(json)\(dd)]"
                    } else {
                        json = json + dd + ","
                    }
                }
                
                //can
                if ggvc.type4web {
                    // web时清空formdata数据，由网页自己处理数据保存
                    json = ""
                    
                    if (btntitle == "同意" || btntitle == "填写完成")  && webNeedEdit {
                        
                        let topRect = CGRect(x: 0, y: 0, width: 1, height: 1)
                        ggvc.tableView.scrollRectToVisible(topRect, animated: true)
                        
                        
                        ggvc.headerVV.webSaveSuccessClo = {
                            continueBtnAc()
                        }
                        
                        ggvc.headerVV.commonWebview.evaluateJavaScript("saveFlowData()", completionHandler: { (result, error) in
                            //                            if let error = error {
                            //                                KSToast("Error: \(error.localizedDescription)")
                            //                            } else {
                            //                                continueBtnAc()
                            //                            }
                        })
                    } else {
                        continueBtnAc()
                    }
                    
                } else {
                    if btntitle == "同意" || btntitle == "保存单据" {
                        guard vali.validate() else {
                            return
                        }
                    }
                    continueBtnAc()
                }
                
            } else {
                continueBtnAc()
            }
        }
        
         
        func continueBtnAc() {
            
            switch btntitle {
            case "指定改单":
                let vca = AppointVC()
                vca.appointSuccess = {
                    parentVc.navigationController?.popViewController(animated: true)
                }
                vca.selfmodel = selfmodel
                vca.holdPprogress = pointsResult
                parentVc.navigationController?.pushViewController(vca, animated: true)
                
            case "保存单据":
                
                if let provc = parentVc as? ConfigMenuForm {
                    
                    var isRoot = "0"
                    if selfmodel.nodeId == "root" {
                        isRoot = "1"
                    }
                    
                    provc.beginSaveAc(is_root: isRoot)
                } else {
                    KSNetwork.shared.doRequest(API.auditFlow(.saveVouModify(instanceId: selfmodel.instanceId.unwrap, formData: json, formArray: jsonNew))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("保存成功")
                         } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                }
                
            case "填写完成":
                KSNetwork.shared.doRequest(API.auditFlow(.updateModifvou(id_key: selfmodel.id.unwrap))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        KSToast("成功")
                        parentVc.navigationController?.popViewController(animated: true)
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
            case "同意","评论","取消提交","催办",refuseTitle:// 同意
                
                showSubmitV(btntitle: btntitle, json: json, jsonNew: jsonNew, targetUser: "", nodeId: "", desc: btntitle)
         
            case "已阅":
                KSNetwork.shared.doRequest(API.auditFlow(.WflowUpdateNOTIFY(instanceId: selfmodel.instanceId.unwrap, id: selfmodel.id.unwrap))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        KSToast("成功")
                        parentVc.navigationController?.popViewController(animated: true)
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
                        
            case "知会":
               
                KSNetwork.shared.doRequest(API.auditFlow(.WflowgetStaffName(page: "1", size: "10000", c_name: "", org_name: ""))) { (data:BaseResult<ToDoPerson>) in
                    if data.flag == TRUE {
                        if let infos = data.infoArrCombine {
                            var allArr = [(ToDoPerson,Bool)]()
                            for i in 0..<infos.count {
                                 allArr.append((infos[i],false))
                            }
                            let cle:([Any])->() = { arr in
                                
                                let nmarr = arr.compactMap{ ($0 as! ToDoPerson).c_name }.joined(separator: ",")
                                let idarr = arr.compactMap{ ($0 as! ToDoPerson).id_key }.joined(separator: ",")

                                let vvv = ComAlertV()
                                var opS = [nameBtnAction]()
                                
                                opS = [nameBtnAction(name: "确认", action: { _ in
                             
                                    let textStr = vvv.fieldArr[0].1.text.unwrap
                                    guard textStr != "" else {
                                        KSToast("填写知会内容")
                                        return
                                    }
                                   
                                    KSNetwork.shared.doRequest(API.auditFlow(.WflowMoreCcTask(instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap, usrid: idarr, comment: textStr))) { (data:BaseResult<ToDoPerson>) in
                                        if data.flag == TRUE {
                                            KSToast("知会成功")
                                            
                                        } else {
                                            KSToast(data.errorCombine.unwrap)
                                        }
                                        vvv.dismiss()
                                        
                                    }
                                }),nameBtnAction(name: "取消", action: { _ in
                                    vvv.dismiss()
                                })]
                                vvv.add(title: "知会给\(nmarr)", message: "",textFields:["知会内容"], operateS: opS)
                                vvv.present()
  
                            }
                            
                            let listShowC: ((GlobalTableViewCell, Any) -> ()) = { cell, model in
                                var contArr:[(String,String?)]!
                                contArr = [
                                           ("","\((model as! ToDoPerson).c_name.unwrap)")
                                        ]
                               cell.setDataSource(contentArr: contArr)
                            }
                            
                            let filterC: ((Any, String) -> (Bool)) = { model, keyword -> Bool in
                                return (model as! ToDoPerson).c_name.unwrap.contains(keyword)
                            }
                            
                            let selShowC: ((MultiSeTextCell, Any) -> ()) = { cell, model in
                                 cell.btn.setTitle("\((model as! ToDoPerson).c_name.unwrap)", for: .normal)
                            }
                            
                            let mulVC = KSMultiSelectUtil.initWithNav(title: "知会", allArr: allArr, backClosure: cle,kSShowCell: listShowC , filterClosure: filterC,kSSelShowCell: selShowC)
 
                            let topViewController = RouterUtils.currentTopViewController()
                            topViewController!.present_FullScreen(to: mulVC)
                            
                        }
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
            case "移交","加签":
                let tstr = btntitle == "移交" ? "选择移交人员" : "选择加签人员"
//                let ttype = btntitle == "移交" ? "transfer" : "afterAdd"
                
                let vc = KSSingleSelectNetUtil(searchType: .bar)
                
                vc.title = tstr
                
                vc.kSSingleSelectNetNetwork = { page,size,keyword in
                    KSNetwork.shared.doRequest(API.auditFlow(.WflowgetStaffName(page: "\(page)", size: "\(size)", c_name: keyword, org_name: ""))) { (data:BaseResult<ToDoPerson>) in
                        if data.flag == TRUE {
                            if let infos = data.infoArrCombine {
                                if page == 1 {
                                    vc.allArr.removeAll()
                                }
                                vc.showData(arr:infos)
                            }
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                }
                
                vc.kSSingleSelectNetShowCell = { cell,model in
                    
                    var contArr:[(String,String?)]!
                    
                    contArr = [
                        ("姓名","\((model as! ToDoPerson).c_name.unwrap)"),
                        ("部门","\((model as! ToDoPerson).c_dept_name.unwrap)"),
                    ]
                    
                    cell.setDataSource(contentArr: contArr)
                }
                
                vc.backClosure = {model in
                    
                    let targetUser = (model as! ToDoPerson).id_key.unwrap
                    let targetUserNm = (model as! ToDoPerson).c_name.unwrap

                    showSubmitV(btntitle: btntitle, json: json, jsonNew: jsonNew,targetUser:targetUser,nodeId:"",desc:"\(btntitle):\(targetUserNm)")
                    
                }
                
                parentVc.navigationController?.pushViewController(vc,animated:true)
                
            case backTitle:
                 
                let vc = KSSingleSelectNetUtil()
                
                vc.title = "选择"
                
                vc.kSSingleSelectNetNetwork = { page,size,keyword in
                    KSNetwork.shared.doRequest(API.auditFlow(.Wflowrecallnodes(instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap))) { (data:BaseResultOK<ReCallNode>) in
                        if data.flag == TRUE || (checkPlatform(type: .zhuYouAn) && data.message == "获取成功") {
                            if let infos = data.infoArrCombine {
                                if page == 1 {
                                    vc.allArr.removeAll()
                                }
                                vc.showData(arr:infos)
                            }
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                }
                
                vc.kSSingleSelectNetShowCell = { cell,model in
                    
                    var contArr:[(String,String?)]!
                    
                    contArr = [
                        ("角色","\((model as! ReCallNode).nodeName.unwrap)"),
                        
                    ]
                    cell.setDataSource(contentArr: contArr)
                    
                }
                
                vc.backClosure = {model in
                    
                    let nodeId = (model as! ReCallNode).nodeId.unwrap
                    let nodeNm = (model as! ReCallNode).nodeName.unwrap

                    showSubmitV(btntitle: btntitle, json: json, jsonNew: jsonNew, targetUser: "", nodeId: nodeId,desc:"\(btntitle):\(nodeNm)")
                     
                }
                parentVc.navigationController?.pushViewController(vc,animated:true)
                
       
            default:
                break
            }
        }
    }
    
 
    
    func showSubmitV(btntitle: String, json: String, jsonNew: String, targetUser: String, nodeId: String, desc: String) {
        let submitV = AuditSubmitView(chooseUser: chooseuser, vc: parentVc)
        submitV.descLab.text = desc
        submitV.submitBtn.setTitle(btntitle, for: .normal)
        submitV.submitBtn.addTouchUpInSideAction { btnx in
            //审核节点选人
            var chooseUserjson = ""
            if submitV.chooseUser.count > 0 && btntitle.contains("同意")  {
                
                let vali = Validation()
                for onex in submitV.chooseUser {
                    vali.required(value: submitV.chooseUserDic[onex.nodeId.unwrap], msg: "审核节点必填")
                }
                guard vali.validate() else {
                    return
                }
                
                var pp = "["
                for (key,value) in submitV.chooseUserDic {
                    
                    pp += "{\"\(key)\":\"\(value)\"},"
                }
                pp.removeLast()
                
                chooseUserjson = pp + "]"
                 
            }
             
            let memoStr = submitV.auditTextBg.audittext.text.unwrap
            let files = submitV.imgArr
     
            continueSave()


            func continueSave() {
            
                submitV.dismiss()
                
                
                switch btntitle {
          
               
                case "同意":// 同意
                    
                    var commentStr = memoStr
                    if commentStr == "" {
                        commentStr = "同意"
                    }

                    KSNetwork.shared.doRequest(API.auditFlow(.wflowhander(voc_cd:selfmodel.vocCd.unwrap,vou_id: selfmodel.vouId.unwrap,instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap,nodeId: selfmodel.nodeId.unwrap, signature: "", agree: "agree", comment: commentStr, targetNode: "", targetUser: "",formData: json,formArray: jsonNew,otherNodeUsers: chooseUserjson,file: files))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("成功")
                            parentVc.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                case "评论":
                    guard memoStr != "" else {
                        KSToast("填写评论内容")
                        return
                    }
                    
                    KSNetwork.shared.doRequest(API.auditFlow(.wflowhander(voc_cd:selfmodel.vocCd.unwrap,vou_id: selfmodel.vouId.unwrap,instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap,nodeId: selfmodel.nodeId.unwrap, signature: "", agree: "comment", comment: memoStr, targetNode: "", targetUser: "",formData: json,formArray: jsonNew,otherNodeUsers: "",file: files))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("成功")
                            parentVc.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                    
                case "取消提交":
                    guard memoStr != "" else {
                        KSToast("填写取消提交原因")
                        return
                    }

                    KSNetwork.shared.doRequest(API.auditFlow(.cancelSubmit(comment: memoStr, voc_cd: selfmodel.vocCd.unwrap, vouid: selfmodel.vouId.unwrap,vou_id: selfmodel.vouId.unwrap))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("成功")
                            parentVc.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }

                case "催办":
                    
                    guard memoStr != "" else {
                        KSToast("填写催办内容")
                        return
                    }
                    
                    KSNetwork.shared.doRequest(API.auditFlow(.saveCbinfo(instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap, nodeId: selfmodel.nodeId.unwrap, voc_cd: selfmodel.vocCd.unwrap, vou_id: selfmodel.vouId.unwrap, comment: memoStr))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("成功")
                             parentVc.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
 
                case "移交","加签":
//                    let tstr = btntitle == "移交" ? "选择移交人员" : "选择加签人员"
                    let ttype = btntitle == "移交" ? "transfer" : "afterAdd"
 
                    KSNetwork.shared.doRequest(API.auditFlow(.wflowhander(voc_cd:selfmodel.vocCd.unwrap,vou_id: selfmodel.vouId.unwrap,instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap,nodeId: selfmodel.nodeId.unwrap, signature: "", agree: ttype, comment: memoStr, targetNode: "", targetUser: targetUser,formData: json,formArray: jsonNew,otherNodeUsers: chooseUserjson,file: files))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            
                            parentVc.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                    
                case backTitle:
                     
                    KSNetwork.shared.doRequest(API.auditFlow(.wflowhander(voc_cd:selfmodel.vocCd.unwrap,vou_id: selfmodel.vouId.unwrap,instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap,nodeId: selfmodel.nodeId.unwrap, signature: "", agree: "recall", comment: memoStr, targetNode: nodeId, targetUser: "",formData: json,formArray: jsonNew,otherNodeUsers: "",file: files))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            parentVc.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                case refuseTitle:
             
                    var commentStr = memoStr
                    if commentStr == "" {
                        commentStr = "拒绝"
                    }
                    KSNetwork.shared.doRequest(API.auditFlow(.wflowhander(voc_cd:selfmodel.vocCd.unwrap, vou_id: selfmodel.vouId.unwrap, instanceId: selfmodel.instanceId.unwrap, taskId: selfmodel.taskId.unwrap, nodeId: selfmodel.nodeId.unwrap, signature: "", agree: "refuse", comment: commentStr, targetNode: "", targetUser: "", formData: json, formArray: jsonNew, otherNodeUsers: "", file: files))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("成功")
                            parentVc.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                default:
                    break
                }
            }
        }
 
        submitV.present()
    }
    
    return (auditProcessV,auditOpeV)
}

func showUserInfoArray(idkey: String) {
    
    KSNetwork.shared.doRequest(API.auditFlow(.getUserInfoArray(id_key: idkey))) { (data:BaseResult<AuditUserModel>) in
        if data.flag == TRUE {
            if let userA = data.infoArrCombine {
                
                let view = UIView()
                view.backgroundColor = .white
                view.frame = CGRect(x:20,y:100,width:KSGlobal.screenW - 40,height:KSGlobal.screenH - 200)
                
                let newsView = UserInfoTable()
                newsView.dataArray = userA
                
                newsView.frame = view.bounds
                view.addSubview(newsView)
                //                newsView.layer.masksToBounds = true
                //                newsView.layer.cornerRadius = 12
                
                let topViewController = RouterUtils.currentTopViewController()!
                topViewController.lew_presentPopupView( view, animation: LewPopupViewAnimationSpring()) {
                    print("动画结束")
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
            
        } else {
            KSToast(data.errorCombine.unwrap)
        }
    }
}


extension GeneralAuditForm {
    
    // MARK: - TableView DataSource And Delegate
    func numberOfSections(in tableView: UITableView) -> Int {
        if type4web {
            return 0
        } else {
            if isUseTab {
                return self.dataArray.count + self.showTabDataArr.count
            } else {
                return self.dataArray.count
            }
        }
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if type4web {
            return 0
            
        } else {
            var one: AuditFlowContent
            
            if isUseTab {
                if section < self.dataArray.count {
                    one = self.dataArray[section]
                } else {
                    one = self.showTabDataArr[section - self.dataArray.count]
                }
            } else {
                one = self.dataArray[section]
            }
            
            if one.openx {
                if one.type == "1" {
                    return one.mainArr.count
                    
                } else if one.type == "3" {
                    return 1
                    
                } else if one.type == "2" {
                    return one.detailArr.count
                    
                } else if one.type == "4" {
                    return one.files.count
                    
                } else {
                    return 0
                }
            } else {
                return 0
            }
        }
        // #warning Incomplete implementation, return the number of rows
    }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if type4web {
            
            // 没用到，阻止报错，后续优化
            let cell = tableView.dequeueReusableCell(withIdentifier: GeneralSepeCell.identifier, for: indexPath) as! GeneralSepeCell
            return cell
            
        } else {
            let section = indexPath.section
            var one: AuditFlowContent
            
            if isUseTab {
                if section < self.dataArray.count {
                    one = self.dataArray[section]
                } else {
                    one = self.showTabDataArr[section - self.dataArray.count]
                }
            } else {
                one = self.dataArray[section]
            }
            
            if isUseTab && one.type == "2" {
                let cell = tableView.dequeueReusableCell(withIdentifier: AuditItemCell2.identifier) as! AuditItemCell2
                
                let tempArr = one.detailArr[indexPath.row]
                cell.titlex = tempArr.pre
                cell.contentx = tempArr.suf
                cell.conType = tempArr.conType
                if tempArr.perm == "E" {
                    cell.editable = true
                } else {
                    cell.editable = false
                }
                cell.mustLab.isHidden = (tempArr.must == "false")
                cell.moreBlock = { [weak self] in
                    let vc = GeneralAuditDetailForm()
                    vc.dataArray = tempArr.moreInfo
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
                
                return cell
            } else if one.type == "2" && one.detailArr[indexPath.row].conType == .seperate {
                let cell = tableView.dequeueReusableCell(withIdentifier: GeneralSepeCell.identifier, for: indexPath) as! GeneralSepeCell
                
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: AuditItemCell.identifier, for: indexPath) as! AuditItemCell
                
                if one.type == "1" {
                    let tempArr = one.mainArr[indexPath.row]
                    cell.titlex = tempArr.pre
                    cell.contentx = tempArr.suf
                    cell.conType = tempArr.conType
                    
                    // 发起人节点都可以编辑
                    if tempArr.perm == "E" || model.nodeId == "root" {
                        cell.editable = true
                    } else {
                        cell.editable = false
                    }
                    if tempArr.must == "true" {
                        cell.mustLab.isHidden = false
                    } else {
                        cell.mustLab.isHidden = true
                    }
                    
                    cell.contentLab.addTextChangeClosure {[indexPath] tev in
                        //todo
                        self.dataArray[indexPath.section].mainArr[indexPath.row].suf = tev.text
                    }
                    
                } else if one.type == "2" {
                    let tempArr = one.detailArr[indexPath.row]
                    cell.titlex = tempArr.pre
                    cell.contentx = tempArr.suf
                    cell.conType = tempArr.conType
                    if tempArr.perm == "E" {
                        cell.editable = true
                    } else {
                        cell.editable = false
                    }
                    cell.mustLab.isHidden = (tempArr.must == "false")
                    
                } else if one.type == "3" {
                    
                    cell.titlex = ""
                    cell.contentx = one.title.unwrap
                    cell.conType = .report
                    cell.editable = false
                    
                } else if one.type == "4" {
                    
                    cell.contentx = one.files[indexPath.row].file_name.unwrap
                    cell.titlex = ""
                    cell.conType = .file
                    
                }
                return cell
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = indexPath.section
        var one: AuditFlowContent
        
        if isUseTab {
            if section < self.dataArray.count {
                one = self.dataArray[section]
            } else {
                one = self.showTabDataArr[section - self.dataArray.count]
            }
        } else {
            one = self.dataArray[section]
        }
        
        if one.type == "1" {
            let tt = one.mainArr[indexPath.row].pre
            if  tt.contains("招标编号")  || tt.contains("竞拍编号") {
                
            }
            
        } else if one.type == "3" {
            go2ChartForWeb_OA(url: BaseReportUrl, path: one.report.unwrap, title: "报表", parameters: [:], currentVC: self)
            
        } else if one.type == "4" {
            if one.files[indexPath.row].pic_url.unwrap != "" {
                let rwerwr = configURL(latter:one.files[indexPath.row].pic_url.unwrap)
                let cwebV = CommonWebController()
                cwebV.reportUrl = rwerwr
                cwebV.title = one.files[indexPath.row].file_name
                self.navigationController?.pushViewController(cwebV, animated: true)
                
            } else {
                KSNetwork.shared.doRequest(API.auditFlow(.getAuditApprovaFile(id_key: one.files[indexPath.row].id_key.unwrap,file_name: one.files[indexPath.row].file_name.unwrap)), successHandle: { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        if let infostr = data.infoStr {
                            let rwerwr = configURL(latter:"\(infostr)")
                            let cwebV = CommonWebController()
                            cwebV.reportUrl = rwerwr
                            cwebV.title = one.files[indexPath.row].file_name
                            self.navigationController?.pushViewController(cwebV, animated: true)
                        }
                        
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                })
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        var model: AuditFlowContent
        
        if isUseTab {
            if section < self.dataArray.count {
                model = self.dataArray[section]
            } else {
                model = self.showTabDataArr[section - self.dataArray.count]
            }
        } else {
            model = self.dataArray[section]
        }
        
        if isUseTab {
            if model.type == "2" {
                return 50
            }
            if model.type == "11" {
                return 15
            }
        }
        
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        var model: AuditFlowContent
        
        if isUseTab {
            if section < self.dataArray.count {
                model = self.dataArray[section]
            } else {
                model = self.showTabDataArr[section - self.dataArray.count]
            }
        } else {
            model = self.dataArray[section]
        }
        
        if model.type == "10" {
            return tabSectionHeader
        }
        
        if model.type == "11" {
            let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: GeneralAuditTabFooter.identifier)
            return footer
        }
        
        if isUseTab && model.type == "2" {
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: GlobalSectionHeader.identifier) as! GlobalSectionHeader
            header.setTitle(model.title)
            header.delBtn.extHidden(hidden: true)
            header.setOpenx(flag: model.openx)
            
            let tap = UITapGestureRecognizer()
            tap.numberOfTapsRequired = 1
            tap.addTap { [unowned self] _ in
                if isUseTab {
                    if section < self.dataArray.count {
                        self.dataArray[section].openx = !self.dataArray[section].openx
                    } else {
                        self.showTabDataArr[section - self.dataArray.count].openx = !self.showTabDataArr[section - self.dataArray.count].openx
                    }
                } else {
                    self.dataArray[section].openx = !self.dataArray[section].openx
                }
                
                let set = IndexSet(integer:section)
                tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
            }
            
            header.addGestureRecognizer(tap)
            
            return header
        }
        
        guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: AuditSecHeader.identifier) as? AuditSecHeader else {
            fatalError()
        }
        
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            
            if isUseTab {
                if section < self.dataArray.count {
                    self.dataArray[section].openx = !self.dataArray[section].openx
                } else {
                    self.showTabDataArr[section - self.dataArray.count].openx = !self.showTabDataArr[section - self.dataArray.count].openx
                }
            } else {
                self.dataArray[section].openx = !self.dataArray[section].openx
            }
            
            let set = IndexSet(integer:section)
            tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
        }
        
        headerView.addGestureRecognizer(tap)
        
        if model.openx {
            headerView.arrow.setBackgroundImage(UIImage(named: "af_arrow_down"), for: .normal)
        } else {
            headerView.arrow.setBackgroundImage(UIImage(named: "af_arrow_right"), for: .normal)
        }
  
        headerView.lab.text = model.title
        return headerView
    }
}
